package com.zjh.photoshopstudy.app.user;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.zjh.photoshopstudy.Model.AppUserEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.App;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.Utils.SharePreferencesUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserFragment extends Fragment {
    ImageView imageView;
    TextView name;
    TextView tip;

    public UserFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        AppUserEntity appUserEntity = SharePreferencesUtils.getLoginUser(getContext());
        View view = null;
        if (appUserEntity != null) {
            view = inflater.inflate(R.layout.fragment_user, container, false);
            imageView = view.findViewById(R.id.imageView2);
            name = view.findViewById(R.id.textView3);
            tip = view.findViewById(R.id.comment_tip);
            initView(new UpdateUser());
        } else {
            view = inflater.inflate(R.layout.fragment_user2, container, false);
        }

        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void initView(UpdateUser e) {
        AppUserEntity user = SharePreferencesUtils.getLoginUser(getContext());
        Glide.with(getContext()).load(Data.webRoot_URL + user.getuIcon()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imageView);
        name.setText(user.getuName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getNewComment(GetNewComment e) {
        int uid = (int) SharePreferencesUtils.getLoginUser(App.getContext()).getId();
        int count = SharePreferencesUtils.getNewCommentCount(getContext(), uid);
        if (e.getList().size() > count) {
            tip.setVisibility(View.VISIBLE);
        } else {
            tip.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public static class UpdateUser {
    }

}
